<?php

namespace App\Http\Api\Services;

use App\Exceptions\InvalidRequestException;
use App\Http\Models\Order;
use App\Http\Models\Product;
use App\Http\Models\ProductSku;
use App\Http\Models\ProductsShops;
use App\Http\Services\BaseService;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;


class ProductListService extends BaseService
{

    public function dataChange($attributes = [])
    {
        if(empty($attributes['type'] || empty($attributes['key']) || empty($attributes['no']))){
            throw new InvalidRequestException('参数缺失！');
        }
        try{
            if($attributes['type'] == 'prod'){
                Product::where('prod_no',$attributes['no'])->update([$attributes['key']=>$attributes['value']]);
            }elseif($attributes['type'] == 'sku'){
                ProductSku::where('sku_no',$attributes['no'])->update([$attributes['key']=>$attributes['value']]);
            }

        }catch (\Exception $e){
            throw new InvalidRequestException($e->getMessage());
        }


        return true;
    }

    public function delProd($attributes = []){
        if(empty($attributes['sku_no'])){
            throw new InvalidRequestException('参数缺失！');
        }
        try{
            ProductSku::where('sku_no',$attributes['sku_no'])->delete();

        }catch (\Exception $e){
            throw new InvalidRequestException($e->getMessage());
        }


        return true;
    }

    public function addProd($attributes = []){
        if(empty($attributes['sku_size']) || empty($attributes['sku_color']) || empty($attributes['prod_no']) || empty($attributes['sku_price'])){
            throw new InvalidRequestException('参数缺失！');
        }
        try{
            $attributes['sku_no']   =   $attributes['prod_no'].'_'.$attributes['sku_color'].'_'.$attributes['sku_size'];
            $exists =    ProductSku::where('sku_no',$attributes['sku_no'])->exists();
            if(!$exists){

                ProductSku::insert($attributes);

            }

        }catch (\Exception $e){
            throw new InvalidRequestException($e->getMessage());
        }


        return true;
    }

    //校验店铺商品上架情况
    public function checkShopProd($attributes = []){
        if(empty($attributes['prod_no']) || empty($attributes['shop_id'])){
            throw new InvalidRequestException('参数缺失！');
        }
        $result =   false;
        try{
            $exists =    ProductsShops::where('prod_no',$attributes['prod_no'])->where('shop_id',$attributes['shop_id'])->exists();
            if(!$exists){

                $result =   false;

            }else{
                $result =   true;
            }

        }catch (\Exception $e){
            throw new InvalidRequestException($e->getMessage());
        }

        return $result;

    }

}